<template>
  <div class="app-container">
    <el-tree
      :data="treeData"
      node-key="id"
      default-expand-all
      :expand-on-click-node="true"
      :props="defaultProps"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button type="text" size="mini" @click="handleEdit(node, data)">
            编辑
          </el-button>
          <el-button type="text" size="mini" @click="() => handleDel(node, data)">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>
  </div>
</template>

<script>
import subjectApi from "@/api/subject";
import { listToTreeList } from "@/utils/index";
export default {
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: "children",
        label: "title",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取数据列表并转化为树形结构
    async getList() {
      let res = await subjectApi.getAllSubject();
      if (res.success) {
        let tempList = res.data.list;
        this.treeData = listToTreeList(tempList);
      }
    },
    handleEdit(node, data) {
      let id = data.id;
      if (id) {
        this.$router.push({
          path: "/subject/save",
          query: { id },
        });
      }
    },
    handleDel(node, data) {
      let id = data.id;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(()=>{
        this.del(id)
      })
    },
    async del(id) {
      let res = await subjectApi.deleteSubject(id);
      if(res.success) {
        this.$message.success("删除成功")
        this.getList()
      }else {
        return this.$message.error("删除失败")
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>